// this function is for test purpose only, remove from production copy
function loadPerson(){
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest("OWNER"), 'owner');
	req.send(loadPersonHandler);
}

function loadPersonHandler(data){
	owner = data.get('owner').getData();
	//removeTestPurchaseData(o.getId());
	
	loadPurchaseData();
			
	/*
	for(var i=0; i<globalPurchaseData.length; i++){
		getContentInfo(globalPurchaseData[i]);
	}*/
}

/*function removeTestPurchaseData(personId){
	var req = opensocial.newDataRequest();
			req.add(req.newRemovePersonAppDataRequest(personId,'*'));
	req.send(removeDataHandler);
}

function removeDataHandler(data){
	addPurchaseData();
}*/

function loadPurchaseData(){
	var req = opensocial.newDataRequest();
	var powner = opensocial.newIdSpec({"userId" : "OWNER"});
	req.add(req.newFetchPersonAppDataRequest(powner, 'ringtones'), 'rt');
	
	//req.add(req.newUpdatePersonAppDataRequest("OWNER",'ringtones',globalPurchaseData));
	req.add(req.newFetchPersonRequest("OWNER"), 'owner');
	
	req.send(loadPurchaseHandler);
}

function loadPurchaseHandler(data){
	var rtones = data.get("rt").getData();
	var o = data.get("owner").getData();
	var mytones = gadgets.json.parse(gadgets.util.unescapeString(rtones[o.getId()]["ringtones"]));
	
	for(var i=0; i<mytones.length; i++){
		globalPurchaseData.push(mytones[i]);
	}
	
	if(newPurchaseId != null){
		globalPurchaseData.push(newPurchaseId);
		addPurchaseData();
		newPurchaseId = null;
	}
	
	if(mytones.length > 0){
		getContentInfo(globalPurchaseData[globalPurchaseData.length - 1]);
	} else if(mytones.length <= 0 && globalView == "profile"){
		showProfileView();
	}
}

function addPurchaseData(){
	var json = gadgets.json.stringify(globalPurchaseData);
	
	var req = opensocial.newDataRequest();
	req.add(req.newUpdatePersonAppDataRequest("OWNER",'ringtones',json));
	req.add(req.newFetchPersonRequest("OWNER"), 'owner');
				
	var powner = opensocial.newIdSpec({"userId" : "OWNER"});
	req.add(req.newFetchPersonAppDataRequest(powner, 'ringtones'), 'rt');
	
	req.send(addPurchaseHandler);
}

function addPurchaseHandler(data){
	var rtones = data.get("rt").getData();
	var o = data.get("owner").getData();
	owner = o;
	var mytones = gadgets.json.parse(gadgets.util.unescapeString(rtones[o.getId()]["ringtones"]));
	var rtString = "";
	
	getContentInfo(mytones[mytones.length - 1]);
}

function getContentInfo(contentId) {
	var url = "http://api.hosted.thumbplay.com/api/rest/offers/partnerLinks?contentIds="+encodeURI(contentId)+"&pname=1456&plpFlow=atb4";
	var tpParams = {};
        tpParams[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM; 
	gadgets.io.makeRequest(url, getContentInfoHandler, tpParams);
}

function getContentInfoHandler(obj){
	if(typeof obj != 'undefined' && typeof obj.data != 'undefined'){
		var data = obj.data;
		var errors = data.getElementsByTagName('errors');
		
		if(errors.length == 0){
			var contentNodes = data.getElementsByTagName('offerLinks');
			if(contentNodes.length > 0){
				for(var i=0; i<contentNodes.length; i++){
					var olChilds = contentNodes[i].childNodes;
					var contentId;
					var title;
					for(var j=0; j<olChilds.length; j++){
						if(olChilds[j].nodeName == 'contentId'){
							contentId = olChilds[j].firstChild.nodeValue; 
						} else if(olChilds[j].nodeName == 'titleLandingPageURL'){
							title = getReqParam(olChilds[j].firstChild.nodeValue, 'thptitle');
						}
					}
					
					if((typeof contentId != "undefined") && (typeof title != "undefined")
						&& contentId != null && contentId != ""
						&& title != null && title != ""){
						getRingtoneInfo(contentId, title);
					}
				}
			}
		}
	}
}

function getRingtoneInfo(contentId, title){
	var url = "http://api.hosted.thumbplay.com/api/rest/search/content?title="+encodeURI(title)+"&pname=1456";
	var tpParams = {};
        tpParams[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM; 
	gadgets.io.makeRequest(url, function(o){
								ringtoneInfoHandler(o, contentId);
						   }, tpParams);
}

function ringtoneInfoHandler(dat, contentId){
	if(typeof dat != 'undefined' && typeof dat.data != 'undefined'){
		var data = dat.data;
		var errors = data.getElementsByTagName('errors');
		
		if(errors.length == 0){
			var contentNodes = data.getElementsByTagName('contentResult');
			if(contentNodes.length > 0){
				for(var i=0; i<contentNodes.length; i++){
					var info = new Object();
					var cn = contentNodes[i].childNodes;
					
					for(var j=0; j<cn.length; j++){
						currNode = cn.item(j); 
						n = currNode.nodeName;
						var cid;
						switch(n){
							case "contentId":
								cid = currNode.firstChild.nodeValue;
								break;
							case "title":
								info.title = currNode.firstChild.nodeValue;
								break;
							case "titleLandingPageURL":
								info.titleLanding = currNode.firstChild.nodeValue;
								break;
							case "artist":
								if(currNode.firstChild != null){
									info.artist = currNode.firstChild.nodeValue;
								} else {
									info.artist = "Unknown";									
								}
								break;
							case "artistLandingPageURL":
								info.artistLanding = currNode.firstChild.nodeValue;
								break;
							case "imageSmallURL":
								info.image = currNode.firstChild.nodeValue;
								break;
							case "previewURL":
								info.preview = currNode.firstChild.nodeValue;
								break;
						}
					}
					
					if(cid == contentId){						
						rInfo.push(info);
						
						if(globalView == "profile"){
							createView();
						} else if(globalView == "canvas"){
							if(hasNewRingtone == "true") {
								createActivityFeed(rInfo[rInfo.length - 1]);
							}
						}
					}
				}
			} else {
				var info = new Object();
				info.error = "Not Found";
				rInfo.push(info);
			}
		} else {
			var info = new Object();
			info.error = "Not Found";
			rInfo.push(info);
		}
	} else {
		var info = new Object();
		info.error = "Not Found";
		rInfo.push(info);
	}
	
	/*if(rInfo.length == globalPurchaseData.length){
		
	}*/
}

function createActivityFeed(newPurchase){
	//for(var i=0; i<rInfo.length; i++) {
		//var title = owner.getDisplayName()+" purchased <a href=\""+rInfo[0].titleLanding+"\">"+rInfo[0].title+"</a> by <a href=\""+rInfo[0].artistLanding+"\">"+rInfo[0].artist+"</a>";
		var title = "";
		if(typeof newPurchase.title != 'undefined'){
			title = owner.getDisplayName()+" purchased <a href=\""+newPurchase.titleLanding+"\" target=\"_blank\">"+newPurchase.title+"</a> by <a href=\""+newPurchase.artistLanding+"\" target=\"_blank\">"+newPurchase.artist+"</a>";
			
			var params = {};
			var opt_params = {};
			params[opensocial.Activity.Field.TITLE] = title;
			
			var mediaItems = new Array();
			var imageUrl = newPurchase.image;
			var mimeType = "";
			
			if(newPurchase.image.lastIndexOf(".jpg") != -1  || newPurchase.image.lastIndexOf("jpeg") != -1){
				mimeType = "image/jpeg";
			} else if(newPurchase.image.lastIndexOf(".png") != -1){
				mimeType = "image/png";
			} else if(newPurchase.image.lastIndexOf(".gif") != -1){
				mimeType = "image/gif";
			}
			
			if(mimeType != ""){
				var imageParams = {};
				imageParams[opensocial.MediaItem.Field.TYPE] = opensocial.MediaItem.Type.IMAGE;
				var imageItem = opensocial.newMediaItem(mimeType, imageUrl, imageParams);
				mediaItems[0] = imageItem;
				params[opensocial.Activity.Field.MEDIA_ITEMS] = mediaItems;
			}		
			
			/*var mediaItems = new Array();
			//opt_params[opensocial.MediaItem.Field.MIME_TYPE] = "image/jpeg";
			var mediaItem = opensocial.newMediaItem(opensocial.MediaItem.Type.IMAGE, "http://cdn.preview.thumbplay.com/VAN/Cover_Art/75/UMG/UMG_cvrart_00602517834880_01_RGB72_450x450_1842200.jpg");
			mediaItem.setField(opensocial.MediaItem.Field.MIME_TYPE, "image/jpeg");
			mediaItems[0] = mediaItem;
			params[opensocial.Activity.Field.MEDIA_ITEMS] = mediaItems;*/
			//params[opensocial.Activity.Field.STREAM_FAVICON_URL] = newPurchase.image;
			var activity = opensocial.newActivity(params)
					opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function(status) {
						if(status.hadError()){
							alert(status.getErrorMessage());
						}
					});
			hasNewRingtone = "false";
		}
	//}
}

function showProfileView(){
	var profileData = null;
	
	if(rInfo.length > 0){
		profileData = rInfo[rInfo.length - 1];
	}
	
	html += '<div id="profile_container">';
	//for(var i=0; i<rInfo.length; i++){
		if(profileData != null && (typeof profileData.error == 'undefined') 
			&& profileData.title != null && profileData.title != ""){
			html += "<img src=\""+profileData.image+"\" onclick=\"gotoCanvas()\"/>";
			html += '<div id="profile_content">';
			html += "<a href=\"#\"><img src=\""+base_url+"/images/playbtn.png\" class=\"stopped\" style=\"padding-right:5px;border:none\" onclick=\"createFlashEmbed('"+profileData.preview+"',this,'profile');return false;\"/></a>";
			html += "<a href=\""+profileData.titleLanding+"\" target=\"_blank\" style=\"font-weight:bold;\">"+profileData.title+"</a><br/>";
			html += "by <a href=\""+profileData.artistLanding+"\" target=\"_blank\">"+profileData.artist+"</a>";								
			html += '</div>';
		} else {
			html += '<p style="font-weight:bold">No purchased ringtones found.</p>';
		}			
	//}
	html+= '<div id="profile_footer">';
	html += '<p>Thumbplay <span>Personalize your phone</span></p>';
	html += '</div>';
	html += '</div>';
		
	document.getElementById('profile_module').style.display = "";
	document.getElementById('profile_module').innerHTML = html;
}

// demo function showing how to insert view param
function gotoCanvas(){
	var vp = {};
	vp["newTone"] = "true";
	vp["contentid"] = "12345";
	var v = gadgets.views.getSupportedViews()['canvas'];
	gadgets.views.requestNavigateTo(v,vp);
}